home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
MacHack 1996
/
MacHack 1996.toast
/
Presentations
/
Presentations ’94
/
Timothy Knox
/
Help
/
Help Files
/
Miscellaneous
/
Memoizing
< prev
next >
Wrap
Text File
|
1994-06-24
|
1KB
|
48 lines
{••• Let's have fun with memo-functions •••}
{••• A function that looks for a memoized value •••}
{••• o = look for it, t = in it, s = access result •••}
{••• f = thunk to evaluate upon failure •••}
(define (lookup o t s f)
(letrec [((lookup t)
(cond (null? t) (f)
(let [(pr (0 t))]
(cond (equal? (0 pr) o) (s pr)
(lookup (-1 t))))))]
(lookup t)))
{••• The memoizer itself, p is the function to memoize •••}
{••• s is CDR access (-1) and f memoizes •••}
(define (memo p)
(let [(t ())]
(lambda a
(lookup a
t
-1
(lambda()
(let [(v (apply p a))]
(=! t (force (cons (cons a v) t)))
v))))))
{••• A small macro to extend the Help language •••}
(defmacro (defmemo f | b)
(cond (cons? f) `(define ,(0 f) (memo (lambda ,(-1 f) ,@b)))
`(define ,f (memo ,@b))))
{••• An example with a memoized NAIVE fibonnacci •••}
(defmemo (f n)
(cond (<? n 2) 1
(+ (f (1- n))(f (- n 2)))))
{••• Timing on a SE-30 •••}
(chrono (f 100))
{ = [573147844013817084101 7.500000000000000000e-1 0.000000000000000000e+0] }
{••• Now it's memoized… let's try again •••}
(chrono (f 100))
{ = [573147844013817084101 0.000000000000000000e+0 0.000000000000000000e+0] }